package org.lex.ftp.model;

import java.io.IOException;

import org.lex.catalog.AbstractCatalogModel;
import org.lex.net.ftp.FTPURL;
import org.lex.net.ftp.IFTPClient;
import org.lex.net.ftp.IFTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AbstractFTPModel extends AbstractCatalogModel<String> implements FTPModel {
	private static final IFTPFile[] EMPTY = new IFTPFile[0];

	private final Logger log = LoggerFactory.getLogger(AbstractFTPModel.class);
	private FTPFileView view = null;
	private IFTPClient ftp = null;
	private FTPURL ftpURL = FTPURL.FAKE_URL;
	// ---------------------------
	private String directory = "/";
	private IFTPFile[] lists = EMPTY;
	private String[] names = null;

	public AbstractFTPModel() {
		view = new SimpleFTPFileView();
	}

	public FTPURL getFTPURL() {
		return this.ftpURL;
	}

	public void setFTPURL(FTPURL url) {
		this.ftpURL = url;
	}

	public FTPFileView getFTPFileView() {
		return view;
	}

	public void setFTPFileView(FTPFileView ftpFileView) {
		if (null != ftpFileView) {
			this.view = ftpFileView;
			this.fireCatalogChanged(this.getCatalog());
		}
	}

	public IFTPClient getFTPClient() {
		return this.ftp;
	}

	public void setFTPClient(IFTPClient ftp) {
		this.ftp = ftp;
	}

	public String getCatalog() {
		return directory;
	}

	public void cdUp() {
		try {
			this.ftp.cdUp();
			this.doList();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setCatalog(String directory) {
		try {
			this.ftp.cwd(directory);
			this.doList();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public IFTPFile[] list() {
		return lists;
	}

	public String[] getChildren() {
		if (null == this.names) {
			names = new String[lists.length];
			for (int i = 0; i < lists.length; i++)
				names[i] = lists[i].getName();
		}
		return names;
	}

	private void doList() throws IOException {
		this.directory = this.ftp.pwd();
		log.trace("enter directory: {}", this.directory);
		this.lists = this.ftp.list();
		this.names = null;
		this.fireCatalogChanged(this.directory);
	}
}
